package com.LeeCode;

import java.util.ArrayList;
import java.util.List;

/**
 * N皇后
 */

public class Code051 {
    public static void main(String[] args) {
        int n = 8;
        System.out.println(new Code051().solveNQueens(n));
    }

    public List<List<String>> solveNQueens(int n) {
        List<List<String>> res = new ArrayList<>();
        int[] board = new int[n];
        backtrack(res, board, 0);
        return res;
    }

    public void backtrack(List<List<String>> res, int[] board, int row) {
        if (row == board.length) {
            List<String> list = new ArrayList<>();
            for (int i = 0; i < board.length; i++) {
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < board.length; j++) {
                    if (board[i] == j) {
                        sb.append("Q");
                    } else {
                        sb.append(".");
                    }
                }
                list.add(sb.toString());
            }
            res.add(new ArrayList<>(list));
            return;
        }

        for (int col = 0; col < board.length; col++) {
            if (check(row, col, board)) {
                board[row] = col;
                backtrack(res, board, row + 1);
                board[row] = 0;
            }
        }
    }

    public boolean check(int row, int col, int[] board) {
        for (int i = 0; i < row; i++) {
            if (col == board[i] || Math.abs(row - i) == Math.abs(col - board[i])) {
                return false;
            }
        }
        return true;
    }
}
